package com.dswz.utils;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class HttpClientUtil2 {
	private static Logger logger = LogManager.getLogger(HttpClientUtil.class);
	public static final Integer ConnectTimeout = Integer.valueOf(30000);
	public static final Integer ConnectionRequestTimeout = Integer.valueOf(30000);
	public static final Integer SocketTimeout = Integer.valueOf(30000);
	public static final Boolean StaleConnectionCheckEnabled = Boolean.valueOf(true);
	private static PoolingHttpClientConnectionManager cm = null;

	static {
		cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(400);
		cm.setDefaultMaxPerRoute(50);
		new HttpClientUtil2.IdleConnectionEvictor(cm).start();
	}

	public static String doPost(String url, Map<String, String> params) throws Exception {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.custom().setConnectionManager(cm).build();

			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(getRequestConfig());
			List<NameValuePair> parameters = new ArrayList(0);
			for (Map.Entry<String, String> entry : params.entrySet()) {
				parameters.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
			}
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");

			httpPost.setEntity(formEntity);
			response = httpClient.execute(httpPost);
			logger.info("doPost:response:" + response);

			String content = EntityUtils.toString(response.getEntity(), "UTF-8");
			return content;
		} catch (Exception e) {
			throw e;
		} finally {
			if (response != null) {
				response.close();
				logger.info("doPost:response.close():����������");
			}
		}
	}

	public static String doGet(String url) throws Exception {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.custom().setConnectionManager(cm).build();

			HttpGet httpGet = new HttpGet(url);
			httpGet.setConfig(getRequestConfig());

			response = httpClient.execute(httpGet);
			logger.info("doGet:response:" + response);

			String content = EntityUtils.toString(response.getEntity(), "UTF-8");
			return content;
		} catch (Exception e) {
			throw e;
		} finally {
			if (response != null) {
				response.close();
				logger.info("doGet:response.close():����������");
			}
		}
	}

	public static String doGet(String url, Map<String, String> params) throws Exception {
		URIBuilder builder = new URIBuilder(url);
		for (Map.Entry<String, String> entry : params.entrySet()) {
			builder.setParameter((String) entry.getKey(), (String) entry.getValue());
		}
		return doGet(builder.build().toString());
	}

	public static String doGet2(String url) throws Exception {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.custom().setConnectionManager(cm).build();

			HttpGet httpGet = new HttpGet(url);
			httpGet.setConfig(getRequestConfig());

			response = httpClient.execute(httpGet);
			logger.info("doGet2:response:" + response);

			String content = EntityUtils.toString(response.getEntity(), "GBK");
			return content;
		} catch (Exception e) {
			throw e;
		} finally {
			if (response != null) {
				response.close();
				logger.info("doGet2:response.close():����������");
			}
		}
	}

	public static String doGet2(String url, Map<String, String> params) throws Exception {
		URIBuilder builder = new URIBuilder(url);
		for (Map.Entry<String, String> entry : params.entrySet()) {
			builder.setParameter((String) entry.getKey(), (String) entry.getValue());
		}
		return doGet2(builder.build().toString());
	}

	public static String upload() throws Exception {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.custom().setConnectionManager(cm).build();
			HttpPost httpPost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");

			FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
			StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
			HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
					.build();
			httpPost.setEntity(reqEntity);
			response = httpClient.execute(httpPost);

			String content = EntityUtils.toString(response.getEntity(), "UTF-8");
			return content;
		} catch (Exception e) {
			throw e;
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	public static RequestConfig getRequestConfig() {
		RequestConfig config = RequestConfig.custom().setConnectTimeout(ConnectTimeout.intValue())
				.setConnectionRequestTimeout(ConnectionRequestTimeout.intValue())
				.setSocketTimeout(SocketTimeout.intValue())
				.setStaleConnectionCheckEnabled(StaleConnectionCheckEnabled.booleanValue()).build();
		return config;
	}

	public static void main(String[] args) {
		new HttpClientUtil();

		new HttpClientUtil();

		new HttpClientUtil();
	}

	public static class IdleConnectionEvictor extends Thread {

		private final HttpClientConnectionManager connMgr;

		private volatile boolean shutdown;

		public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
			super();
			this.connMgr = connMgr;
		}

		@Override
		public void run() {
			try {
				while (!shutdown) {
					synchronized (this) {
						wait(5000);
						// Close expired connections
						connMgr.closeExpiredConnections();
						// Optionally, close connections
						// that have been idle longer than 5 sec
						connMgr.closeIdleConnections(5, TimeUnit.SECONDS);
					}
				}
			} catch (InterruptedException ex) {
				// terminate
			}
		}

		public void shutdown() {
			shutdown = true;
			synchronized (this) {
				notifyAll();
			}
		}

	}

}
